package com.ay.service;

import com.ay.utils.HttpUtils;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class XiaohongshuService {
    private static final String BASE_URL = "https://ad-market.xiaohongshu.com/api/v1";
    private final String accessToken;
    
    public XiaohongshuService(String accessToken) {
        this.accessToken = accessToken;
    }
    
    /**
     * 获取广告账户信息
     */
    public JSONObject getAdAccountInfo() throws IOException {
        String url = BASE_URL + "/advertiser/account/info";
        String response = HttpUtils.sendGet(url);
        return new JSONObject(response);
    }
    
    /**
     * 获取广告计划列表
     */
    public JSONObject getAdCampaigns(int page, int pageSize) throws IOException {
        String url = String.format("%s/campaigns?page=%d&page_size=%d", BASE_URL, page, pageSize);
        String response = HttpUtils.sendGet(url);
        return new JSONObject(response);
    }
    
    /**
     * 获取广告创意列表
     */
    public JSONObject getAdCreatives(int page, int pageSize) throws IOException {
        String url = String.format("%s/creatives?page=%d&page_size=%d", BASE_URL, page, pageSize);
        String response = HttpUtils.sendGet(url);
        return new JSONObject(response);
    }
    
    /**
     * 获取广告数据报表
     */
    public JSONObject getAdReport(String startDate, String endDate, String metrics) throws IOException {
        String url = String.format("%s/report?start_date=%s&end_date=%s&metrics=%s", 
            BASE_URL, startDate, endDate, metrics);
        String response = HttpUtils.sendGet(url);
        return new JSONObject(response);
    }
    
    /**
     * 获取广告账户信息（带分页）
     */
    public JSONObject getAdAccountInfo(String requestBody, Map<String, String> headers) throws IOException {
        String url = BASE_URL + "/advertiser/account/info";
        String response = HttpUtils.sendPost(url, requestBody, headers);
        return new JSONObject(response);
    }
    
    /**
     * 分页获取所有账户信息
     */
    public void getAllAdAccountInfo(String userId, ChannelAdvertisersMapper mapper) throws IOException {
        int page = 1;
        int pageSize = 500;
        boolean hasMore = true;
        
        while (hasMore) {
            JSONObject requestBody = new JSONObject()
                .put("user_id", userId)
                .put("page", String.valueOf(page))
                .put("page_size", String.valueOf(pageSize));
                
            Map<String, String> headers = Map.of(
                "access-token", Objects.requireNonNull(HttpClientHelper.getByAdToKen("1"))
            );
            
            JSONObject response = getAdAccountInfo(JSONUtil.toJsonStr(requestBody), headers);
            JSONObject data = response.getJSONObject("data");
            int total = Integer.parseInt(data.getString("total"));
            
            if (total == 0) {
                hasMore = false;
                continue;
            }
            
            JSONArray accounts = data.getJSONArray("sub_accounts");
            List<ChannelAdvertisers> batchAccounts = new ArrayList<>();
            
            for (int i = 0; i < accounts.length(); i++) {
                JSONObject accountInfo = accounts.getJSONObject(i);
                ChannelAdvertisers entityData = getEntityData(accountInfo);
                batchAccounts.add(entityData);
                
                // 当批次达到500条时，执行批量插入或更新
                if (batchAccounts.size() >= 500) {
                    mapper.insertOrUpdateBatch(batchAccounts);
                    batchAccounts.clear();
                }
            }
            
            // 处理剩余的记录
            if (!batchAccounts.isEmpty()) {
                mapper.insertOrUpdateBatch(batchAccounts);
            }
            
            // 检查是否还有更多数据
            if (page * pageSize >= total) {
                hasMore = false;
            } else {
                page++;
            }
        }
    }
    
    /**
     * 将JSON数据转换为实体对象
     */
    private ChannelAdvertisers getEntityData(JSONObject accountInfo) {
        ChannelAdvertisers entity = new ChannelAdvertisers();
        entity.setId(accountInfo.getString("id"));
        entity.setName(accountInfo.getString("name"));
        entity.setStatus(accountInfo.getString("status"));
        // ... 设置其他字段
        return entity;
    }
} 